package com.rdk.action;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rdk.constant.CodeConstant;
import com.rdk.constant.Forward;
import com.rdk.constant.StrConstant;
import com.rdk.entity.ChatDataBean;
import com.rdk.entity.CheckRequstParam;
import com.rdk.entity.CheckResponseEntity;
import com.rdk.entity.DataBean;
import com.rdk.entity.IndexEntity;
import com.rdk.entity.IndexRequest;
import com.rdk.entity.KwsParam;
import com.rdk.entity.KwsRequestParam;
import com.rdk.entity.KwsResponseEntity;
import com.rdk.entity.KwsResult;
import com.rdk.entity.PSKeyWord;
import com.rdk.entity.vo.SerieBean;
import com.rdk.entity.vo.Stauts;
import com.rdk.service.CheckUserService;
import com.rdk.service.PSKeyWordService;
import com.rdk.service.PublicSentimentService;
import com.rdk.service.impl.CheckUserServiceImpl;
import com.rdk.service.impl.PSKeyWordServiceImpl;
import com.rdk.service.impl.PublicSentimentServiceImpl;
import com.rdk.utils.CommonUtil;
import com.rdk.utils.StringUtil;
import com.rdk.utils.TimeUtil;
import com.rdk.wechat.util.JSONutils;

/**
 * 舆情分析
 * 
 * @author wanglei
 *
 */
@Controller
@RequestMapping(value = "sentiment")
public class SentimentAction extends BaseAction {

	/**
	 * 舆情首页
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "toIndex")
	public String toIndex(HttpServletRequest request, ModelMap map) {

		// 设置userToken
		String userToken = CommonUtil.getRequest(request, "userToken");
		CheckRequstParam userParma = new CheckRequstParam();
		userParma.setUserAgentNo(userToken);

		CheckUserService checkUserService = new CheckUserServiceImpl();
		CheckResponseEntity ce = checkUserService.getUserAccount(userParma);
		String firstGID = ce.getFirstGID();

		String nowDate = TimeUtil.getNowDate();
		String startTime = nowDate + " 00:00:00";
		String endTime = TimeUtil.getNowDateHS();

		IndexRequest ir = new IndexRequest();
		ir.setEndTime(endTime);
		ir.setStartTime(startTime);
		ir.setUserAgentNo(userToken);
		ir.setKey(firstGID);
		ir.setLimit(StrConstant.LIST_LIMIT_10);

		// 获取舆情指数(总数，正负值)
		PublicSentimentService psService = new PublicSentimentServiceImpl();
		IndexEntity indexEntity = psService.getIndexInfo(ir);

		boolean keyWordIsNull = Boolean.valueOf(CommonUtil.getSession(request, "keyWordIsNull"));
		
		map.put("keyWordIsNull", keyWordIsNull);

		System.out.println(indexEntity);
		map.put("indexEntity", indexEntity);
		return Forward.AjaxPage.SENTIMENT_INDEX;
	}

	/**
	 * 舆情列表页
	 * 
	 * @param request
	 * @param map
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "toList")
	public String toList(HttpServletRequest request, ModelMap map) throws UnsupportedEncodingException {

		// 设置userToken
		String userToken = CommonUtil.getRequest(request, "userToken");
		String keyWord = (String) CommonUtil.getRequestObj(request, "keyWord");
		String keyWordTemp = "";
		
		// 本地测试用，发表前请注释掉
		//----------------------------------------------------------------------------------------------------
//		String keyWord= new String(request.getParameter("keyWord").toString().getBytes("iso8859_1"), "utf-8");
		//----------------------------------------------------------------------------------------------------
				
		
		
		if (keyWord != null){
			String[] keyWordArray = keyWord.split(" ");
			
			int keyWordArrayLength = keyWordArray.length;
			for (int i = 0; i<keyWordArrayLength; i++){
				if (!"".equals(keyWordArray[i])){
					if (i < keyWordArrayLength -1){
						keyWordTemp += keyWordArray[i] + ";";
					}else{
						keyWordTemp += keyWordArray[i];
					}
				}
			}
		}
		
		System.out.println(keyWordTemp);
		
		// userToken = "15850593063";
		String firstGID = this.getFirstGID(userToken);

		List<DataBean> dataList = this.getDataList(userToken, firstGID, keyWordTemp, 1);
		System.out.println(dataList);
		
		if (StringUtil.isNotEmpty(keyWord)){
			map.put("keyWord", keyWord);
		}
		
		Set<String> kwss = this.getKeyWord(request, userToken, null);
		
		map.put("kwss", kwss);
		
		map.put("dataList", dataList);

		return Forward.ActionPage.SENTIMENT_LIST;
	}

	/**
	 * 舆情列表页
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "toList1")
	public String toList1(HttpServletRequest request, ModelMap map) {

		// 设置userToken
		String userToken = CommonUtil.getRequest(request, "userToken");
		String keyWord = (String) CommonUtil.getRequestObj(request, "keyWord");
		
		String keyWordTemp = "";
		
		String[] keyWordArray = keyWord.split(" ");
		
		int keyWordArrayLength = keyWordArray.length;
		for (int i = 0; i<keyWordArrayLength; i++){
			if (!"".equals(keyWordArray[i])){
				if (i < keyWordArrayLength -1){
					keyWordTemp += keyWordArray[i] + ";";
				}else{
					keyWordTemp += keyWordArray[i];
				}
			}
		}
		
		System.out.println(keyWordTemp);

		// userToken = "15850593063";
		String firstGID = this.getFirstGID(userToken);

		List<DataBean> dataList = this.getDataList(userToken, firstGID, keyWord, 1);
		System.out.println(dataList);
		map.put("keyWord", keyWord);
		map.put("dataList", dataList);

		return Forward.ActionPage.SENTIMENT_LIST1;
	}

	/**
	 * 舆情列表页--加载页面用
	 * 
	 * @param request
	 * @param map
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "addList")
	public String addList(HttpServletRequest request, ModelMap map) throws UnsupportedEncodingException {

		// 设置userToken
		String userToken = CommonUtil.getRequest(request, "userToken");
		String keyWord = (String) CommonUtil.getRequestObj(request, "keyWord");
		int currentPage = Integer.valueOf(CommonUtil.getRequest(request, "pageNum"));
		
		// 本地测试用，发表前请注释掉
		//----------------------------------------------------------------------------------------------------
//		String keyWord= new String(request.getParameter("keyWord").toString().getBytes("iso8859_1"), "utf-8");
		//----------------------------------------------------------------------------------------------------
		
		String keyWordTemp = "";
		
		if (StringUtil.isNotEmpty(keyWord)){
			String[] keyWordArray = keyWord.split("_");
			
			int keyWordArrayLength = keyWordArray.length;
			for (int i = 0; i<keyWordArrayLength; i++){
				if (!"".equals(keyWordArray[i])){
					if (i < keyWordArrayLength -1){
						keyWordTemp += keyWordArray[i] + ";";
					}else{
						keyWordTemp += keyWordArray[i];
					}
				}
			}
		}
		
		System.out.println(keyWordTemp);

		//
		// userToken = "15850593063";
		String firstGID = this.getFirstGID(userToken);

		List<DataBean> dataList = this.getDataList(userToken, firstGID, keyWordTemp, currentPage);
		System.out.println(dataList);
		map.put("dataList", dataList);

		return Forward.ActionPage.SENTIMENT_ADD_LIST;
	}

	/**
	 * 舆情详情页
	 * 
	 * @param request
	 * @param map
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "toDesc")
	public String toDesc(HttpServletRequest request, ModelMap map) {

		String userToken = CommonUtil.getRequest(request, "userToken");
		String psId = (String) CommonUtil.getRequestObj(request, "pid");
		String xKey = request.getParameter("xKey");
		
		//----------------------------------------------------------------------------------------------------
		//---------------------------------- 本地测试用，发布前请注释掉 --------------------------------------
		// String xKey= new String(request.getParameter("xKey").toString().getBytes("iso8859_1"), "utf-8");
		//----------------------------------------------------------------------------------------------------
		
		Set<String> kwss = this.getKeyWord(request, userToken, xKey);
		String firstGID = this.getFirstGID(userToken);
		PublicSentimentService psService = new PublicSentimentServiceImpl();

		IndexRequest ir = new IndexRequest();
		ir.setUserAgentNo(userToken);
		ir.setKey(firstGID);
		ir.setPsId(psId);
		List<DataBean> dataList = psService.getPSById(ir);
		
		
		// updata wanglei 20160312 修改： 内容关键词高亮处理 start
		if (null != dataList){
			String content = dataList.get(0).getContent();
		
			// 根据字的长度排序，长度降序
			TreeMap<Integer,String> mapDesc = this.getMapDesc(kwss);
			
			/*
			 * 字数最长的词组最先进行高亮替换，避免包含词组无法匹配替换
			 * 例如：太极拳，杨式太极拳，先替换字数最长的为：<font>杨式太极拳</font>, 太极拳
			 * 在替换字数少的为:<font>杨式<font>太极拳</font></font>, <font>太极拳</font>
			 * 可以保证两个词组都能被替换掉
			 */
			for(Entry<Integer, String> enrty : mapDesc.entrySet()){
				String kws = enrty.getValue();
				String temp = "<font style=\"color:red\">" + kws + "</font>";
				content = content.replace(kws, temp);
			}
			
			dataList.get(0).setContent(content);
		}
		// updata wanglei 20160312 修改： 内容关键词高亮处理 ends
		System.out.println(dataList);

		DataBean dataBean = dataList.get(0);
		map.put("dataBean", dataBean);

		return Forward.ActionPage.SENTIMENT_DESC;
	}
	
	/**
	 * map排序，降序
	 * @param key
	 * @param val
	 * @return
	 */
	private TreeMap<Integer,String> getMapDesc(Set<String> list){
		
		TreeMap<Integer,String> map2= new TreeMap<Integer,String>(new Comparator<Integer>(){  
            /*  
            * int compare(Object o1, Object o2) 返回一个基本类型的整型，  
            * 返回负数表示：o1 小于o2，  
            * 返回0 表示：o1和o2相等，  
            * 返回正数表示：o1大于o2。  
            */    
           public int compare(Integer a,Integer b){  
               return b-a;           
           }  
        
		});  
		for(String s : list){
			map2.put(s.length(), s);
		}
		
		return map2;
	}
	
	/**
	 * 
	 * @param request
	 * @param userToken
	 * @param xKey
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Set<String> getKeyWord(HttpServletRequest request, String userToken, String xKey){
		
		Set<String> kwss = (Set<String>)CommonUtil.getSessionObj(request, "kwss");
		
		if (null == kwss){
			kwss = new HashSet<String>();
			// 设置userToken
			String firstGID = this.getFirstGID(userToken);
			KwsRequestParam kwsRequestParam = new KwsRequestParam();
			kwsRequestParam.setUserAgentNo(userToken);
			kwsRequestParam.setCurrentPage(1);
			
			// 获取关键字
			PSKeyWordService psKeyWord = new PSKeyWordServiceImpl();
			KwsResult kws = psKeyWord.getAllkws(kwsRequestParam, firstGID);
			
			if(kws != null && kws.getData() != null && kws.getData().size()>0 && kws.getData().get(0).getKwsmodel1() !=null && kws.getData().get(0).getKwsmodel1() !=null){
				for(String t : kws.getData().get(0).getKwsmodel1().split(",")){  
					kwss.add(t);  
				}
			}
		}
		
		
		
		if (StringUtil.isNotEmpty(xKey)){
			String[] keyWordArray = xKey.split("_");
			int keyWordArrayLength = keyWordArray.length;
			for (int i = 0; i<keyWordArrayLength; i++){
				if (!"".equals(keyWordArray[i])){
					kwss.add(keyWordArray[i]);
				}
			}
		}
		
		return kwss;
	}

	/**
	 * 关注词设置页
	 * 
	 * @param request
	 * @param map
	 * @return
	 * 
	 * 		http://
	 */
	@RequestMapping(value = "toSetUp")
	public String toSetUp(HttpServletRequest request, ModelMap map) {

		PSKeyWordService psKeyWord = new PSKeyWordServiceImpl();

		// 设置userToken
		String userToken = CommonUtil.getRequest(request, "userToken");
		String firstGID = this.getFirstGID(userToken);

		KwsRequestParam kwsRequestParam = new KwsRequestParam();
		kwsRequestParam.setUserAgentNo(userToken);
		kwsRequestParam.setCurrentPage(1);
		// 获取关键字
		KwsResult kws = psKeyWord.getAllkws(kwsRequestParam, firstGID);
		
		List<String> kwss = Arrays.asList(kws.getData().get(0).getKwsmodel1().split(","));
		Set<String> kwsSet = new HashSet<String>();
		for (String kws1: kwss){
			kwsSet.add(kws1);
		}
		
		CommonUtil.setSession(request, "kwss", kwsSet);
		
		map.put("kws", kws);
		return Forward.ActionPage.SENTIMENT_SETUP;
	}

	/**
	 * 保存关键字
	 * 
	 * @param request
	 * @param map
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "saveKeyWord")
	public ModelAndView saveKeyWord(HttpServletRequest request, ModelMap map) {
		Stauts stauts = new Stauts();
		stauts.setResCode(CodeConstant.SUCCESS);
		String userToken = CommonUtil.getRequest(request, "userToken");
		String keyWordList = CommonUtil.getRequest(request, "keyWordList");
		String firstGID = this.getFirstGID(userToken);

		List<Map<String, String>> list = JSONutils.jsonToList(keyWordList);

		PSKeyWordService psKeyWord = new PSKeyWordServiceImpl();

		KwsParam keyWords = new KwsParam();

		List<PSKeyWord> kwds = this.setPSKeyWord(list, userToken);

		keyWords.setKey(firstGID);
		keyWords.setUserAgentNo(userToken);
		keyWords.setKwds(kwds);

		KwsResponseEntity ere = psKeyWord.batchupdataPersonalKwsByUserId(keyWords);
		CommonUtil.setSession(request, "keyWordIsNull",false);
		

		//List<String> kwss = Arrays.asList(kwds.get(0).getKwsmodel1().split(","));
		Set<String> kwss = new HashSet<String>();
		if(kwds != null && kwds.size() > 0 && kwds.get(0).getKwsmodel1() !=null){
			for(String t : kwds.get(0).getKwsmodel1().split(",")){  
				kwss.add(t);  
			}
		}
		CommonUtil.setSession(request, "kwss", kwss);
		System.out.println(ere);
		return new ModelAndView("jsonView", "chat", stauts);
	}

	/**
	 * 统计图表页
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "toCountChat")
	public String toCountChat(HttpServletRequest request, ModelMap map) {

		return Forward.ActionPage.SENTIMENT_COUNTCHAT;
	}

	/**
	 * 根据时间获取统计数据
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value = "getChat")
	public ModelAndView getChat(HttpServletRequest request, ModelMap map) {

		String startTime = CommonUtil.getRequest(request, "startTime");
		String endTime = CommonUtil.getRequest(request, "endTime");
		String userToken = CommonUtil.getRequest(request, "userToken");
		// 设置userToken
		// userToken = "15850593063";
		String firstGID = this.getFirstGID(userToken);
		// String startTime = nowDate + " 00:00:00";

		IndexRequest indexRequest = new IndexRequest();
		indexRequest.setEndTime(endTime.replaceAll("/", "-"));
		indexRequest.setStartTime(startTime.replaceAll("/", "-"));
		indexRequest.setUserAgentNo(userToken);
		indexRequest.setKey(firstGID);

		// 获取舆情指数(总数，正负值)
		PublicSentimentService psService = new PublicSentimentServiceImpl();
		ChatDataBean chatDataBean = psService.searchChat(indexRequest);
		List<Map<String, String>> timeMap = new ArrayList<Map<String, String>>();
		List<SerieBean> series = new ArrayList<SerieBean>();

		if (null != chatDataBean) {
			try {

				Map<String, Map<String, Integer>> chatDataBeanMap = this.getReflect(chatDataBean);

				for (Entry<String, Map<String, Integer>> entry : chatDataBeanMap.entrySet()) {
					SerieBean serieBean = new SerieBean();

					// 处理时间
					if ("TotalNumMap".equals(entry.getKey())) {
						Map<String, Integer> totalNumMap = entry.getValue();
						for (Entry<String, Integer> entryTime : totalNumMap.entrySet()) {
							timeMap.add(this.getTimeMap(entryTime.getKey().toString()));
						}
					}
					if (!"NormalNumMap".equals(entry.getKey()) && !"EmotionTmepMap".equals(entry.getKey())){
						serieBean.setName(entry.getKey());
						serieBean.setData(chatDataBean.transMapToString(entry.getValue()));
						series.add(serieBean);
					}
				}

				System.out.println(timeMap.toString());
				System.out.println(series.toString());
			} catch (Exception e) {
				System.err.println(e.getMessage());
				e.printStackTrace();
			}

		}

		map.put("timeMap", timeMap);
		map.put("series", series);

		return new ModelAndView("jsonView", "chat", series);
	}

	/**
	 * 获取舆情列表数据
	 * 
	 * @param userToken
	 * @param firstGID
	 * @param keyWord
	 * @return
	 */
	private List<DataBean> getDataList(String userToken, String firstGID, String keyWord, int currentPage) {
		List<DataBean> dataList = null;
		String nowDate = TimeUtil.getNowDate();
		String startTime = nowDate + " 00:00:00";
		String endTime = TimeUtil.getNowDateHS();

		IndexRequest ir = new IndexRequest();
		ir.setEndTime(endTime);
		ir.setStartTime(startTime);
		ir.setUserAgentNo(userToken);
		ir.setKey(firstGID);
		ir.setCurrentPage(currentPage);
		ir.setLimit(StrConstant.LIST_LIMIT_20);

		if (StringUtil.isNotEmpty(keyWord)) {
			/*
			 * try { keyWord = new
			 * String(keyWord.getBytes("ISO8859-1"),"UTF-8"); } catch
			 * (UnsupportedEncodingException e) { e.printStackTrace(); }
			 */
			ir.setKeyWord(keyWord);

		}

		// 获取舆情指数(总数，正负值)
		PublicSentimentService psService = new PublicSentimentServiceImpl();
		dataList = psService.searchkws(ir);

		return dataList;
	}

	/**
	 * 设置关键字数据
	 * @param list
	 * @param userToken
	 * @return
	 */
	private List<PSKeyWord> setPSKeyWord(List<Map<String, String>> list, String userToken) {
		List<PSKeyWord> kwds = new ArrayList<PSKeyWord>();

		for (Map<String, String> keymap : list) {

			PSKeyWord psw = new PSKeyWord();
			psw.setKwsgroupName(keymap.get("kwsgroupName"));
			psw.setKwsmodel1(keymap.get("kwsmodel1"));
			psw.setKwsmodel2(keymap.get("kwsmodel2"));
			psw.setKwsrelationship(keymap.get("kwsrelationship"));
			psw.setModelnum(keymap.get("modelnum"));
			psw.setUserAgentNo(userToken);
			kwds.add(psw);
		}

		return kwds;
	}

	private String getFirstGID(String userToken) {
		CheckRequstParam userParma = new CheckRequstParam();
		userParma.setUserAgentNo(userToken);

		CheckUserService checkUserService = new CheckUserServiceImpl();
		CheckResponseEntity ce = checkUserService.getUserAccount(userParma);	
		String firstGID = null;
		if (null != ce){
			
			firstGID = ce.getFirstGID();
		}

		return firstGID;
	}

	private Map<String, String> getTimeMap(String time) {

		Map<String, String> timeMap = new HashMap<String, String>();

		int srtLength = time.length();

		timeMap.put("year", time.substring(0, 4));
		timeMap.put("moon", time.substring(4, 6));
		timeMap.put("day", time.substring(6, 8));
		if (srtLength > 8) {
			timeMap.put("hour", time.substring(8, srtLength));
		}

		System.err.println(timeMap.toString());

		return timeMap;
	}

	@SuppressWarnings("unchecked")
	private Map<String, Map<String, Integer>> getReflect(Object model)
			throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		Map<String, Map<String, Integer>> mapList = new HashMap<String, Map<String, Integer>>();
		Field[] field = model.getClass().getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
		for (int j = 0; j < field.length; j++) { // 遍历所有属性
			String name = field[j].getName(); // 获取属性的名字

			System.out.println("attribute name:" + name);
			name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
			Method m = model.getClass().getMethod("get" + name);
			Map<String, Integer> value = (Map<String, Integer>) m.invoke(model); // 调用getter方法获取属性值
			if (value != null && value.size() > 0) {
				mapList.put(name, value);

			}
			System.out.println("attribute value:" + value.toString());

		}

		System.out.println("attribute value:" + mapList.toString());

		return mapList;
	}

}
